<template>
    <div class="content" v-loading="loading">
        <el-form label-width="80px" ref="formRef" :rules="rules" :model="bannerInfo">
            <el-form-item label="轮播标题" prop="bannrname">
                <el-input type="text" v-model="bannerInfo.bannrname"></el-input>
            </el-form-item>
            <el-form-item label="轮播图片" prop="bannerimg">
                <el-upload :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadImg">
                    <div class="imgBox">
                        <el-icon v-if="tempImg == ''">
                            <Plus />
                        </el-icon>
                        <img :src="tempImg" alt="" v-else>
                    </div>
                </el-upload>
            </el-form-item>
            <el-form-item label="轮播描述">
                <el-input type="text" v-model="bannerInfo.remark" placeholder="暂无描述"></el-input>
            </el-form-item>
            <el-form-item label="轮播链接" prop="bannerLink">
                <el-input type="text" v-model="bannerInfo.link"></el-input>
            </el-form-item>
            <el-form-item label="轮播状态">
                <el-select v-model="bannerInfo.state">
                    <el-option :value="'0'" :label="'下线'"/>
                    <el-option :value="'1'" :label="'上线'"/>
                    <el-option :value="'2'" :label="'废除'"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save(formRef)">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { reqAddBanner, reqEditBanner } from '@/api/common';
import { BannerType } from '@/types/banner';
import { tip } from '@/utils/alert';
import { getBase64 } from '@/utils/commonUse';
import { ElMessage, FormInstance, FormRules, UploadProps, roleTypes } from 'element-plus';
import Cloud from 'leancloud-storage';
import { reactive, ref,watch } from 'vue';
const formRef = ref<FormInstance>()
console.log(formRef.value);
const loading=ref<boolean>(false)
const tempImg = ref<string>('')
const props=defineProps<{
    bannerInfo:BannerType|null
}>()
const emits=defineEmits(['emitChange'])
const bannerInfo = ref<BannerType>({
    bannrname:'',
    bannerimage: '',
    remark: '',
    link: '',
    state: "1",
})
const tempInfo = { ...bannerInfo.value }

watch(()=>props.bannerInfo,(newValue,oldValue)=>{
    if(props.bannerInfo){
        bannerInfo.value={...newValue as BannerType}
        tempImg.value=bannerInfo.value.bannerimage as string
    }else{
        bannerInfo.value=tempInfo
        tempImg.value=''
    }   
})

const changeBool=()=>{
    emits('emitChange',false)
}


const checkTitle = (rules: any, value: any, callback: any) => {
    if (value == "") {
        callback(new Error('请输入轮播图标题'))
    } else {
        callback()
    }
}
const checkImg = (rules: any, value: any, callback: any) => {
    if (value == "") {
        callback(new Error('请上传轮播图'))
    } else {
        callback()
    }
}

const checkLink = (rules: any, value: any, callback: any) => {
    if (value == "") {
        callback(new Error('请输入轮播图链接'))
    } else {
        callback()
    }
}

const uploadImg = (info: any) => {
    getBase64(info.file, (base64: any) => {
        tempImg.value = base64
    })
}


const imgFormat = (base64: any) => {
    let cloudFile = new Cloud.File("banner.png", { base64 });
    return cloudFile.save()
}


const rules = reactive<FormRules>({
    bannrname: [{ validator: checkTitle, trigger: 'blur', required: true }],
    tempimg: [{ validator: checkImg, trigger: 'blur', required: true }],
    link: [{ validator: checkLink, trigger: 'blur', required: true }]
})

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    let arr:string[]=['image/jpeg','image/png']//http://lc-TRsB5Ldk.cn-n1.lcfile.com/Gz3kPLIk99BxhAYXtqzst20cByPaKH1v/banner.png
    if (!arr.includes(rawFile.type)) {
        ElMessage.error('图片格式错误')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB')
        return false
    }
    return true
}

const addBanner = async() => {
    loading.value=true
    let res:any=await imgFormat(tempImg.value)
    bannerInfo.value.bannerimage = res.attributes.url
    delete bannerInfo.value.lid
    console.log(bannerInfo.value);
    reqAddBanner(bannerInfo.value).then(res => {
        loading.value=false
        bannerInfo.value = tempInfo
        tempImg.value = ''
        changeBool()
        tip(res.data.info,'success')
        history.go(0)
    })
}

const editBanner = async() => {
    loading.value=true
    if(tempImg.value!=bannerInfo.value.bannerimage){
        let res:any=await imgFormat(tempImg.value)
        bannerInfo.value.bannerimage = res.attributes.url
    }
    console.log(bannerInfo.value);
    reqEditBanner(bannerInfo.value).then(res => {
        loading.value=false
        tip(res.data.info,'success')
        changeBool()
    })
}
const save = (formRef: FormInstance | undefined) => {
    if (!formRef) return
    formRef.validate((valid) => {
        if (valid) {
            if(props.bannerInfo){
                editBanner()
            }else{
                addBanner()
            }
        }
    })
}

</script>

<style scoped lang="scss">
.content {
    display: flex;
    justify-content: center;

    .el-form {
        .el-form-item {
            width: 400px;

            .el-button {
                width: 400px;
            }
        }

    }

    .imgBox {
        border: 1px solid #dbdbdb;
        width: 320px;
        height: 112px;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 5px;

        img {
            width: 100%;
        }

        .el-icon {
            color: #dbdbdb;
            font-size: 60px;
        }
    }
}</style>